package com.hangzhou.welbeing.welbeinginstrument.fragement;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
import com.google.gson.Gson;
import com.hangzhou.welbeing.welbeinginstrument.R;
import com.hangzhou.welbeing.welbeinginstrument.activity.PersonalInformationActivity;
import com.hangzhou.welbeing.welbeinginstrument.activity.ReleaseSimilarProfilePageFocusedActivity;
import com.hangzhou.welbeing.welbeinginstrument.activity.SettingActivity;
import com.hangzhou.welbeing.welbeinginstrument.adapter.ReleaseMeFragmentAdapter;
import com.hangzhou.welbeing.welbeinginstrument.base.MyApplication;
import com.hangzhou.welbeing.welbeinginstrument.bean.BasicDateBean;
import com.hangzhou.welbeing.welbeinginstrument.bean.EventBusBean;
import com.hangzhou.welbeing.welbeinginstrument.bean.EventZanBean;
import com.hangzhou.welbeing.welbeinginstrument.bean.InformationBean;
import com.hangzhou.welbeing.welbeinginstrument.bean.MyPoUrl;
import com.hangzhou.welbeing.welbeinginstrument.bean.MyPostDateBean;
import com.hangzhou.welbeing.welbeinginstrument.bean.PraiseBean;
import com.hangzhou.welbeing.welbeinginstrument.config.RBConstants;
import com.hangzhou.welbeing.welbeinginstrument.inteface.OnRecyclerViewItemClickListener;
import com.hangzhou.welbeing.welbeinginstrument.inteface.OnRecyclerViewItemZanListener;
import com.hangzhou.welbeing.welbeinginstrument.tool.GlideCircleTransform;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 杭州惟君医疗科技有限公司16
 * Created by 20433 on 2018/1/29
 */

public class releaseMeFragment extends Fragment implements View.OnClickListener{

    @Bind(R.id.fragment_release_me_baseRecyclerView)
    XRecyclerView fragmentReleaseMeBaseRecyclerView;
    private Context mcontext;
    private ReleaseMeFragmentAdapter releaseMeFragmentAdapter;
    private int p = 1;
    private List<MyPostDateBean.DataBean> mlistBean = new ArrayList<>();
    private ReleaseMeFragmentAdapter releaseMeFragmentAdapter1;
    private boolean flag = true;
    private boolean flag_01 = true;
    private boolean flag_02 = true;
    private ImageView iv_setting;
    private ImageView iv_head_portrait;
    private TextView tv_name;
    private TextView tv_labelling;
    private TextView tv_state;
    private RelativeLayout ll_edit_data;
    private RelativeLayout rl_focus_on;
    private TextView tv_focus_on_number;
    private RelativeLayout rl_fans;
    private TextView tv_fans_number;
    private RelativeLayout rl_collect;
    private TextView tv_collect_number;
    private String cus_logo;
    private String cus_name;
    private int thumbUpNumber;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mcontext = context;
        EventBus.getDefault().register(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = View.inflate(mcontext, R.layout.fragment_release_me, null);
        ButterKnife.bind(this, view);
      //  Logger.init("releaseMeFragment");

        LinearLayoutManager layoutManager =   new LinearLayoutManager(mcontext);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        fragmentReleaseMeBaseRecyclerView.setLayoutManager(layoutManager);
        fragmentReleaseMeBaseRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        fragmentReleaseMeBaseRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallRotate);
        fragmentReleaseMeBaseRecyclerView.setArrowImageView(R.mipmap.iconfont_downgrey);
        View header = LayoutInflater.from(mcontext).inflate(R.layout.fragment_release_me_header_01, container,false);
        findHeaderView(header);
        fragmentReleaseMeBaseRecyclerView.addHeaderView(header);
       // fragmentReleaseMeBaseRecyclerView.setPullRefreshEnabled(false);  //TODO 禁止下拉刷新完毕
        fragmentReleaseMeBaseRecyclerView.getDefaultFootView().setNoMoreHint("就这么多了");
        fragmentReleaseMeBaseRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                //flag = true;
                mlistBean.clear();
                loadDate(1);
                if(flag_02){
                    flag_02 = false;
                    loadPersonalInformationDate();
                }

            }

            @Override
            public void onLoadMore() {
                if(flag_01){
                    p++;
                   // Log.e("tag","+++++loadDate+++=======@@@ppppp==============++++"+p);
                    flag_01 = false;
                    flag = false;
                    loadDate(p);
                }

            }
        });
        releaseMeFragmentAdapter1 = new ReleaseMeFragmentAdapter(mcontext,mlistBean);
        fragmentReleaseMeBaseRecyclerView.setAdapter(releaseMeFragmentAdapter1);
       // fragmentReleaseMeBaseRecyclerView.refresh();
        releaseMeFragmentAdapter1.setOnItemClickListener(new OnRecyclerViewItemClickListener() { // TODO 帖子条目点击
            @Override
            public void onItemClick(View view) {
                int postion = fragmentReleaseMeBaseRecyclerView.getChildAdapterPosition(view)-2;
                MyPostDateBean.DataBean datalist = mlistBean.get(postion);

                if(datalist != null ){
                    List<MyPoUrl> mlist = new ArrayList<MyPoUrl>();
                    for (String s : datalist.po_url) {
                        mlist.add(new MyPoUrl(s));
                    }
                    Intent intent = new Intent(mcontext, ReleaseSimilarProfilePageFocusedActivity.class);

                    intent.putExtra("posts_deleted", "releaseMeFragment");
                    intent.putExtra("posts_deleted_id", postion);
                    intent.putExtra("po_id", datalist.po_id);
                    intent.putExtra("po_name", datalist.po_name);
                    intent.putExtra("addtime", datalist.addtime);
                    intent.putExtra("video", datalist.video);
                    intent.putExtra("vpic", datalist.vpic);
                    intent.putExtra("content", datalist.content);
                    intent.putExtra("cat_id", datalist.cat_id);
                    intent.putExtra("cus_id", datalist.cus_id);
                    intent.putExtra("cus_name", cus_name);
                    intent.putExtra("cus_logo",cus_logo);
                    intent.putExtra("hits_like", datalist.hits_like);
                    intent.putExtra("lstate", datalist.lstate);
                    intent.putExtra("col", datalist.col);
                    intent.putExtra("state", "0");
                    intent.putExtra("count", datalist.count);
                    intent.putExtra("lCount", datalist.lCount);
                    intent.putExtra("po_url", (Serializable) datalist.po_url);
                    startActivity(intent);
                }
            }

            @Override
            public void onItemFirstButtonClick(View v, int position) {

            }
        });
        releaseMeFragmentAdapter1.setmOnItemZanClickListener(new OnRecyclerViewItemZanListener() {
            @Override
            public void onItemZanClick(View v, int position, View view) {
                ImageView imageView= (ImageView) v;
                TextView textView= (TextView) view;
                String cat_id_01 =  mlistBean.get(position).cat_id;
                String po_id_01 =  mlistBean.get(position).po_id;
                String thumbUp = textView.getText().toString().trim();
                try {
                    thumbUpNumber = Integer.parseInt(thumbUp);
                    giveLike(cat_id_01,imageView,po_id_01,textView,position);
                } catch (NumberFormatException e) {
                }
            }
        });
        flag = true;
        loadDate(p);
        return view;
    }

    /**
     * @desc
     * */
    private void loadDate(int p) {
        SharedPreferences sp = mcontext.getSharedPreferences("second_app_internal_data", 0);
        String user_id = sp.getString("user_id", "");
        //Log.e("tag","+++++loadDate+++=======@@@30000==============++++"+RBConstants.SERVER_URL + RBConstants.USER_POST_LIST);
        OkHttpUtils
                .post()
                .url(RBConstants.SERVER_URL + RBConstants.USER_POST_LIST)
                .addParams("cus_id", user_id)
                .addParams("p", p + "")
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String strresponse = response.body().string();
                        Gson gson = new Gson();
                       //Log.e("tag","+++++loadDate+++=======@@@30000==============++++"+strresponse);
                        //TODO 数据转换问题    po_url  null
                        final MyPostDateBean myPostDateBean = gson.fromJson(strresponse, MyPostDateBean.class);
                        //Log.e("tag","+++++loadDate+++=======@@@30000==4643765============++++");
                        MyApplication.getmHandler().post(new Runnable() {
                            @Override
                            public void run() {
                                if (myPostDateBean.errorCode == 200) {
                                    flag_01 = true;
                                    List<MyPostDateBean.DataBean> mlist = myPostDateBean.data;
                                    if (mlist != null && mlist.size() > 0) {
                                        mlistBean.addAll(mlist);
                                        if(flag){
                                            if(fragmentReleaseMeBaseRecyclerView != null){
                                                fragmentReleaseMeBaseRecyclerView.refreshComplete(); //TODO 下拉刷新完毕
                                            }
                                        }else{
                                            if(fragmentReleaseMeBaseRecyclerView != null){
                                                fragmentReleaseMeBaseRecyclerView.loadMoreComplete();  //TODO 上拉加载完毕
                                            }

                                        }
                                    }else{
                                        if(fragmentReleaseMeBaseRecyclerView != null){
                                            fragmentReleaseMeBaseRecyclerView.setNoMore(true);
                                        }
                                    }
                                    releaseMeFragmentAdapter1.notifyDataSetChanged();
                                } else {
                                    flag_01 = true;
                                    Toast.makeText(mcontext, myPostDateBean.errorMessage, Toast.LENGTH_SHORT).show();
                                }
                            }
                        });

                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        flag_01 = true;
                        Toast.makeText(mcontext, "没数据了", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });

    }

    /**
     * @desc 查找头部布局
     * */
    private void findHeaderView(View header) {
        iv_setting = (ImageView) header.findViewById(R.id.fragment_release_me_header_01_iv_setting);
        iv_head_portrait = (ImageView) header.findViewById(R.id.fragment_release_me_header_01_iv_head_portrait);
        tv_name = (TextView) header.findViewById(R.id.fragment_release_me_header_01_tv_name);
        tv_labelling = (TextView) header.findViewById(R.id.fragment_release_me_header_01_tv_labelling);
        tv_state = (TextView) header.findViewById(R.id.fragment_release_me_header_01_tv_state);
        ll_edit_data = (RelativeLayout) header.findViewById(R.id.fragment_release_me_header_01_ll_edit_data);

        rl_focus_on = (RelativeLayout) header.findViewById(R.id.fragment_release_me_header_01_rl_focus_on);
        tv_focus_on_number = (TextView) header.findViewById(R.id.fragment_release_me_header_01_tv_focus_on_number);

        rl_fans = (RelativeLayout) header.findViewById(R.id.fragment_release_me_header_01_rl_fans);
        tv_fans_number = (TextView) header.findViewById(R.id.fragment_release_me_header_01_tv_fans_number);

        rl_collect = (RelativeLayout) header.findViewById(R.id.fragment_release_me_header_01_rl_collect);
        tv_collect_number = (TextView) header.findViewById(R.id.fragment_release_me_header_01_tv_collect_number);

        iv_setting.setOnClickListener(this);
        iv_head_portrait.setOnClickListener(this);
        rl_focus_on.setOnClickListener(this);
        rl_fans.setOnClickListener(this);
        rl_collect.setOnClickListener(this);
        loadPersonalInformationDate();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.fragment_release_me_header_01_iv_setting: //设置
                Intent intent =    new Intent(mcontext, SettingActivity.class);
                startActivity(intent);
                break;
            case R.id.fragment_release_me_header_01_iv_head_portrait: //个人信息
                Intent intent_01 =    new Intent(mcontext, PersonalInformationActivity.class);
                startActivity(intent_01);
                break;
            case R.id.fragment_release_me_header_01_rl_focus_on: //关注
//                Intent intent_02 =    new Intent(mcontext, PayAttentionActivity.class);
//                startActivity(intent_02);
                break;
            case R.id.fragment_release_me_header_01_rl_fans: //粉丝
//                Intent intent_3 =    new Intent(mcontext, FansActivity.class);
//                startActivity(intent_3);
                break;
            case R.id.fragment_release_me_header_01_rl_collect: //收藏
//                Intent intent_4 =    new Intent(mcontext, MyCollectionActivity.class);
//                startActivity(intent_4);
                break;
        }
    }
    /**
     * @desc 加载个人中心数据
     * */
    private void loadPersonalInformationDate() {
        SharedPreferences sp = mcontext.getSharedPreferences("second_app_internal_data", 0);
        String user_id = sp.getString("user_id","");
        OkHttpUtils
                .post()
                .url(RBConstants.SERVER_URL+RBConstants.PERSONAL_CENTER)
                .addParams("cus_id", user_id)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String parseNetworkResponse = response.body().string();
                        Gson gson =  new Gson();
                        //Log.e("tag","parseNetworkResponse===4554====="+parseNetworkResponse);
                        final BasicDateBean basicDateBean =  gson.fromJson(parseNetworkResponse,BasicDateBean.class);
                        MyApplication.getmHandler().post(new Runnable() {
                            @Override
                            public void run() {
                            if(basicDateBean.errorCode == 200 ){
                                flag_02 = true;
                               BasicDateBean.DataBean databean =  basicDateBean.data;
                                if(databean != null ){
                                    cus_logo = databean.cus_logo;
                                    Glide.with(mcontext).load("http://oop.welbeing.cn/Public/Uploads/" + cus_logo).transform(new BitmapTransformation[] { new GlideCircleTransform(mcontext) }).placeholder(R.mipmap.head_portrait).error(R.mipmap.head_portrait).crossFade().into(iv_head_portrait);
                                    cus_name = databean.cus_name;
                                    if(cus_name != null && !TextUtils.isEmpty(cus_name)){
                                        tv_name.setText(cus_name);
                                    }
                                   String signature =  databean.signature;
                                    if(signature != null && !TextUtils.isEmpty(signature)){
                                        tv_labelling.setText(signature);
                                    }
                                    String followed =  databean.followed;
                                    if(followed != null && !TextUtils.isEmpty(followed)){
                                        tv_fans_number.setText(followed);
                                    }

                                    String follower =  databean.follower;
                                    if(follower != null && !TextUtils.isEmpty(follower)){
                                        tv_focus_on_number.setText(follower);
                                    }
                                    int col =  databean.col;
                                    tv_collect_number.setText(col+"");
                                }
                            }else{
                                Toast.makeText(mcontext,basicDateBean.errorMessage,Toast.LENGTH_LONG).show();
                            }
                            }
                        });
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        flag_02 = true;
                        Toast.makeText(mcontext,"网络异常",Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }
    /**
     * @desc 点赞
     * @param cat_id_01
     * @param imageView
     * @param po_id_01
     * @param textView     */
    private void giveLike(String cat_id_01, final ImageView imageView, String po_id_01, final TextView textView,final int position) {
        SharedPreferences sp = mcontext.getSharedPreferences("second_app_internal_data", 0);
        String  user_id = sp.getString("user_id","");
        OkHttpUtils
                .post()
                .url(RBConstants.SERVER_URL+RBConstants.PRAISE)
                .addParams("cus_id", user_id)
                .addParams("cat_id", cat_id_01)
                .addParams("po_id", po_id_01)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String praiseParseNetworkResponse =  response.body().string();
                        Gson gson = new Gson();
                        // Log.e(TAG,"praiseParseNetworkResponse======555======>"+praiseParseNetworkResponse);
                        final PraiseBean praiseBean =  gson.fromJson(praiseParseNetworkResponse,PraiseBean.class);
                        MyApplication.getmHandler().post(new Runnable() {
                            @Override
                            public void run() {
                                if(praiseBean.errorCode == 200){
                                    if(praiseBean.errorMessage.equals("点赞成功!")){
                                        if(thumbUpNumber >= 0){
                                            thumbUpNumber = thumbUpNumber +1;
                                            textView.setText(thumbUpNumber+"");

                                            MyPostDateBean.DataBean datalist = mlistBean.get(position);
                                            datalist.lstate = 1;
                                            datalist.hits_like = thumbUpNumber;
                                            mlistBean.set(position,datalist);
                                        }

                                        imageView.setImageResource(R.mipmap.zanz_00);
                                        Toast.makeText(mcontext,"点赞成功",Toast.LENGTH_LONG).show();
                                    }else if(praiseBean.errorMessage.equals("点赞取消!")){
                                        if(thumbUpNumber >= 1){
                                            thumbUpNumber = thumbUpNumber - 1;
                                            textView.setText(thumbUpNumber+"");
                                            MyPostDateBean.DataBean datalist = mlistBean.get(position);
                                            datalist.lstate = 0;
                                            datalist.hits_like = thumbUpNumber;
                                            mlistBean.set(position,datalist);
                                        }
                                        imageView.setImageResource(R.mipmap.zan_90);
                                        Toast.makeText(mcontext,"取消点赞",Toast.LENGTH_LONG).show();
                                    }
                                }else{
                                    Toast.makeText(mcontext,praiseBean.errorMessage,Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(mcontext,"网络异常",Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if(fragmentReleaseMeBaseRecyclerView != null){
            fragmentReleaseMeBaseRecyclerView.destroy(); // this will totally release XR's memory
            fragmentReleaseMeBaseRecyclerView = null;
        }
    }
    @Subscribe
    public void onEventMainThread(EventBusBean event){
        //接收到发布者发布的事件后，进行相应的处理操作
        if(event.getPosts_deleted().equals("releaseMeFragment")){
            mlistBean.remove(event.getPosts_deleted_id());
            releaseMeFragmentAdapter1.notifyDataSetChanged();
        }
    }

    @Subscribe
    public void onEventMainThread(InformationBean event){

        //接收到发布者发布的事件后，进行相应的处理操作
        if(event.getIdentifier().equals("PersonalInformationActivity")){
           // Log.e(TAG,"stringparseNetworkResponse----44---9------->");
            cus_logo = event.getLogo();
            releaseMeFragmentAdapter1.getDate();
            releaseMeFragmentAdapter1.notifyDataSetChanged();
            Glide.with(mcontext).load("http://oop.welbeing.cn/Public/Uploads/" + cus_logo).transform(new BitmapTransformation[] { new GlideCircleTransform(mcontext) }).placeholder(R.mipmap.head_portrait).error(R.mipmap.head_portrait).crossFade().into(iv_head_portrait);
        }else if(event.getIdentifier().equals("NicknameActivity")){
            //Log.e(TAG,"stringparseNetworkResponse----333---9------->");
            cus_name = event.getLogo();
            tv_name.setText(cus_name);
            releaseMeFragmentAdapter1.getDate();
            releaseMeFragmentAdapter1.notifyDataSetChanged();
        }
    }
    @Subscribe
    public void onEventMainThread(EventZanBean event){
        // Log.e(TAG,"praiseParseNetworkResponse=====进行相应的处理操作=555======>");
        //接收到发布者发布的事件后，进行相应的处理操作
        if(event.getIdentifier().equals("releaseMeFragment")){
            // Log.e(TAG,"praiseParseNetworkResponse=====进行相应的处理操作=releaseFindFragment======>");
            MyPostDateBean.DataBean datalist =   mlistBean.get(event.getPostion());
            datalist.hits_like = event.getHits_like();
            datalist.lstate = event.getLstate1();
            mlistBean.set(event.getPostion(),datalist);
            releaseMeFragmentAdapter1.notifyDataSetChanged();
        }
    }
}
